package com.order.service.impl;

import com.bhudy.exception.SysException;
import com.bhudy.exception.SysExceptionCode;
import com.bhudy.utils.XqhUtils;
import com.order.entity.*;
import com.order.service.*;
import com.bhudy.base.BaseServiceImpl;
import com.bhudy.base.QueryFilter;
import com.sys.utils.ShiroUtils;
import com.sys.utils.Utils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.io.Serializable;
import java.util.*;

/**
 * @Author 卞洪业
 * @Description ResOrderStageServiceImpl
 * @Date Wed Feb 19 17:04:56 CST 2020
 */
@Service
@Transactional
public class ResOrderStageServiceImpl extends BaseServiceImpl<ResOrderStage, Serializable> implements ResOrderStageService {

    @Autowired
    private ResOrderService resOrderService;
    @Autowired
    private ResOrderStageTemplateService resOrderStageTemplateService;

    @Override
    public Object insert(Map<String, Object> resOrderStageMap) {
        Integer stage = Utils.formatInt(resOrderStageMap.get("stage"));
        Integer status = Utils.formatInt(resOrderStageMap.get("status"));
        Long userId = Utils.formatLong(resOrderStageMap.get("userId"));
        Integer evaluateScore = Utils.formatInt(resOrderStageMap.get("evaluateScore"));
        String evaluate = String.valueOf(resOrderStageMap.get("evaluate"));
        String content = String.valueOf(resOrderStageMap.get("content"));
        ResOrder resOrder = resOrderService.get(String.valueOf(resOrderStageMap.get("resOrderId")));

        if (status == null) throw new SysException(SysExceptionCode.CODE_40032);
        if (resOrder == null) throw new SysException(SysExceptionCode.CODE_40002);

        this.insertResOrderStage(resOrder, content);
        if (resOrder.getStage().equals(ResOrder.Stage.FINISH.code) || stage.equals(ResOrder.Stage.FINISH.code)) {
            // 关闭结单阶段
            this.finishStage(resOrder, status, evaluateScore, evaluate);
        } else {
            // 正常状态流程
            this.stage(resOrder, status, userId);
        }

        resOrderService.update(resOrder);
        return resOrderService.getResOrderById(Utils.formatLong(resOrderStageMap.get("resOrderId")));
    }

    /**
     * 结单阶段的处理
     */
    private void finishStage(ResOrder resOrder, Integer status, Integer evaluateScore, String evaluate) {
        if (!resOrder.getCreateBy().equals(ShiroUtils.getUserId())) throw new SysException(SysExceptionCode.CODE_40013);
        resOrder.setEvaluateScore(evaluateScore);
        resOrder.setEvaluate(evaluate);
        resOrder.setUserId(ShiroUtils.getUserId());
        resOrder.setStage(ResOrder.Stage.FINISH.code);
        if (status.equals(1)) {
            // 结单
            resOrder.setOrderStatus(ResOrder.getOrderStatus(ResOrder.Stage.FINISH.code, 2));
        } else if (status.equals(2)) {
            // 重开项目
            resOrder.setParentId(resOrder.getResOrderId());
            resOrder.setResOrderName("重新发布_" + resOrder.getResOrderName());
            resOrder.setResOrderId(XqhUtils.createId());
            resOrder.setStage(ResOrder.Stage.CREATE.code);
            resOrder.setStageSort(1);
            resOrder.setOrderStatus(ResOrder.getOrderStatus(ResOrder.Stage.CREATE.code, 1));

            resOrderService.insert(resOrder);
        } else if (status.equals(3)) {
            // 关闭工单
            resOrder.setOrderStatus(ResOrder.getOrderStatus(ResOrder.Stage.FINISH.code, 3));
        } else {
            // 非法状态
            throw new SysException(SysExceptionCode.CODE_40032);
        }
    }

    /**
     * 工单流程处理
     */
    private void stage(ResOrder resOrder, Integer status, Long userId) {
        if (resOrder.getStage().equals(ResOrder.Stage.HANDLE.code) && status.equals(1)) {
            // 处理中
            resOrder.setOrderStatus(ResOrder.getOrderStatus(resOrder.getStage(), 2));
            return;
        } else if (resOrder.getStage().equals(ResOrder.Stage.HANDLE.code) && status.equals(3)) {
            // 重新指派人
            resOrder.setUserId(userId);
            return;
        }

        boolean isStatus;
        if (resOrder.getStage().equals(ResOrder.Stage.CREATE.code)) {
            // 创建阶段
            if (status.equals(1)) {
                // 发布操作
                isStatus = true;
            } else {
                // 非法操作
                throw new SysException(SysExceptionCode.CODE_40032);
            }
        } else if (resOrder.getStage().equals(ResOrder.Stage.REVIEW.code)) { // 2
            // 审核阶段，通过或者拒绝
            isStatus = status.equals(1);
        } else if (resOrder.getStage().equals(ResOrder.Stage.HANDLE.code)) { //3
            // 处理阶段
            if (status.equals(1)) {
                // 接单同意操作
                isStatus = true;
            } else if (status.equals(2)) {
                // 接单拒绝操作
                isStatus = false;
            } else if (status.equals(3)) {
                // 接单指派操作
                isStatus = true;
            } else if (status.equals(4)) {
                // 接单处理完成操作
                isStatus = true;
            } else {
                throw new SysException(SysExceptionCode.CODE_40032);
            }
        } else if (resOrder.getStage().equals(ResOrder.Stage.AUDIT.code)) { //4
            // 审计阶段，通过或者拒绝
            isStatus = status.equals(1);
        } else {
            throw new SysException(SysExceptionCode.CODE_40032);
        }

        QueryFilter queryFilter = new QueryFilter();
        if (isStatus) {
            queryFilter.clear().and("resOrderTypeId", resOrder.getResOrderTypeId()).and("stageSort", resOrder.getStageSort() + 1);
            ResOrderStageTemplate resOrderStageTemplate = resOrderStageTemplateService.find(queryFilter);
            if (resOrderStageTemplate == null) throw new SysException(SysExceptionCode.CODE_40034);

            this.setUserId(resOrder, resOrderStageTemplate, userId);// 设置处理人
            resOrder.setStage(resOrderStageTemplate.getStage());// 当前状态
            resOrder.setStageSort(resOrderStageTemplate.getStageSort());// 模板步骤
            resOrder.setOrderStatus(ResOrder.getOrderStatus(resOrder.getStage(), 1));// 设置下阶段的状态码
        } else {
            if (resOrder.getStage().equals(ResOrder.Stage.REVIEW.code) || resOrder.getStage().equals(ResOrder.Stage.HANDLE.code)) { // 2
                if (resOrder.getStage().equals(ResOrder.Stage.HANDLE.code)) {
                    resOrder.setOrderStatus(ResOrder.getOrderStatus(ResOrder.Stage.CREATE.code, 3));
                } else {
                    resOrder.setOrderStatus(ResOrder.getOrderStatus(ResOrder.Stage.CREATE.code, 2));
                }
                resOrder.setStage(ResOrder.Stage.CREATE.code);
                resOrder.setStageSort(1);
                resOrder.setUserId(resOrder.getCreateBy());// 设置处理人
            } else if (resOrder.getStage().equals(ResOrder.Stage.AUDIT.code)) { //4
                String sql = "select user_id userId, stage_sort stageSort from res_order_stage where res_order_id = ? and stage = 3 order by sort limit 0,1";
                queryFilter.clear().putArgs(resOrder.getResOrderId());
                List<Map<String, Object>> userIdMapList = super.findMapList(sql, queryFilter);
                if (Utils.isBlank(userIdMapList) && userIdMapList.size() != 0) {
                    resOrder.setUserId(Utils.formatLong(userIdMapList.get(0).get("userId")));
                    resOrder.setStageSort(Utils.formatInt(userIdMapList.get(0).get("stageSort")));
                } else {
                    throw new SysException(SysExceptionCode.CODE_40032);
                }
                resOrder.setStage(ResOrder.Stage.HANDLE.code);
                resOrder.setOrderStatus(ResOrder.getOrderStatus(ResOrder.Stage.HANDLE.code, 3));
            }
        }
    }


    /**
     * 创建ResOrderStage信息
     */
    private void insertResOrderStage(ResOrder resOrder, String content) {
        QueryFilter queryFilter = new QueryFilter();
        // 获取当前阶段模板
        queryFilter.clear().and("resOrderTypeId", resOrder.getResOrderTypeId()).and("stageSort", resOrder.getStageSort()).limit(0, 1);
        ResOrderStageTemplate resOrderStageTemplate = resOrderStageTemplateService.find(queryFilter);
        ResOrderStage orderStage = super.find(queryFilter.clear().and("resOrderId", resOrder.getResOrderId()).orderDESC("sort").limit(0, 1));
        if (resOrderStageTemplate == null) throw new SysException(SysExceptionCode.CODE_40034);

        ResOrderStage resOrderStage = new ResOrderStage();
        if (!(resOrder.getStage().equals(ResOrder.Stage.FINISH.code) &&
                resOrder.getStageSort().equals(ResOrder.getOrderStatus(ResOrder.Stage.FINISH.code, 3)))) {
            resOrderStage.setTemplateName(resOrderStageTemplate.getTemplateName());
        } else {
            resOrderStage.setTemplateName("关闭工单");
        }
        resOrderStage.setResOrderId(resOrder.getResOrderId());
        resOrderStage.setStage(resOrder.getStage());
        resOrderStage.setOrderStatus(resOrder.getOrderStatus());
        resOrderStage.setStageSort(resOrder.getStageSort());
        resOrderStage.setSort(orderStage != null ? (orderStage.getSort() + 1) : 1);
        resOrderStage.setContent(content);
        resOrderStage.setUserId(ShiroUtils.getUserId());
        resOrderStage.setUseTime(orderStage == null ? 0 : (new Date().getTime() - orderStage.getCreateDate().getTime()));
        if (resOrderStageTemplate.getKpi() != null && !resOrderStageTemplate.getKpi().equals(0) && resOrderStage.getUseTime() != null && !resOrderStage.getUseTime().equals(0)) {
            resOrderStage.setQualified((Utils.formatDouble(resOrderStageTemplate.getKpi() - resOrderStage.getUseTime()) / Utils.formatDouble(resOrderStageTemplate.getKpi()) * 100.0));
        }
        super.insert(resOrderStage);
    }

    /**
     * 设置处理人
     */
    private void setUserId(ResOrder resOrder, ResOrderStageTemplate resOrderStageTemplate, Long userId) {
        Long nextUserId;
        if (userId != null && !userId.equals("")) {
            // 处理人指定下阶段处理人
            nextUserId = userId;
        } else if (resOrderStageTemplate.getStage().equals(ResOrder.Stage.FINISH.code)) {
            // 下阶段是结单处理人就是创建人
            nextUserId = resOrder.getCreateBy();
        } else {
            // 获取模板里面的处理人
            nextUserId = resOrderStageTemplate.getUserId();
        }

        if (nextUserId == null || userId.equals("")) throw new SysException(SysExceptionCode.CODE_40036);

        resOrder.setUserId(nextUserId);
    }

}
